/**
 * 
 */
package nl.samenloop.bigscreen.fx;

import javax.swing.JComponent;

/**
 * @author Bram Wiekens
 * 
 */
public class FadeOut {

	private FadeOut() { /* Utility class doesn't have public constructor */
	}

	public static void start(final JComponent component, int duration, final FxListener listener){
		if (component instanceof Transparency) {

			final Transparency target = (Transparency) component;

		
			final float step = FxUtil.calcStepSize(duration);

			component.setIgnoreRepaint(true);
			component.setDoubleBuffered(true);
			
			Thread fadeOut = new Thread(new Runnable() {

				@Override
				public void run() {
					while (target.getOpacity() > 0.0f) {
						target.setOpacity(target.getOpacity() - step);
						if (target.getOpacity() < 0) {
							target.setOpacity(0.0f);
						}

						component.repaint();

						FxUtil.sleep();
					}

					component.setVisible(false);
					
					if (listener != null) {
						listener.finished();
					}
				}
			});

			fadeOut.start();
		} else {
			throw new IllegalStateException("Cannot set Transparency on object");
		}
	}
	
	public static void start(final JComponent component, int duration) {
		start(component, duration,null);
	}

}
